// goods/pages/createOrder/createOrder.js
let myRequest = require('../../../common/script/myRequest.js');
let api = require('../../../common/script/api.js');
let utils = require('../../../utils/util');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsId: '',
    goodsNum: '',
    storeId: '',
    couponHint: '',
    user_note: {},
    cart_form_data: {},
    address: null,
    address_id: '',
    cart2Data: null,
    cart3Data: null,
    http: api.http,
    showCoupon: false,
    showModal: false,
    concent_list: ['微信支付', '会员卡支付'],
    curIndex: 0,
    action: 'buy_now',
    getGoodsTypes: [{
        id: 0,
        value: '快递',
        checked: true,
        isShow: true
      },
      {
        id: 1,
        value: '自提',
        isShow: true
      },

    ],
    sm: 0,
    master_order_sn: ''
  },
  // 修改配送方式
  radioChange(e) {
    const that = this;
    that.setData({
      sm: e.detail.value
    })
    that.getCart3Data()
  },
  // 隐藏模态对话框
  hideModal() {
    const that = this;
    that.setData({
      showModal: false
    });
  },
  // 显示模态对话框
  showModel() {
    const that = this;
    let isVip = wx.getStorageSync('isVip')
    if (isVip) {
      that.setData({
        showModal: true,
        isVip: isVip,
      });
    } else {
      that.debounces()
    }
  },
  // 选择模态框
  choose(e) {
    var index = e.currentTarget.dataset.index
    this.setData({
      curIndex: index
    })
  },
  //显示弹框优惠券
  onCoupon(e) {
    const that = this;
    that.setData({
      showCoupon: true
    });
  },
  //隐藏优惠券弹窗
  hideCoupon() {
    const that = this;
    that.setData({
      showCoupon: false
    })
  },
  //获取优惠券列表
  getCoupon() {
    const that = this;
    let data = {
      goods_id: that.data.action == "buy_now" ? that.data.goodsId : "",
      goods_num: that.data.action == "buy_now" ? that.data.goodsNum : "",
      store_id: that.data.storeId,
      action: that.data.action
    }
    myRequest.EasyHttp.post(api.reqUrls.getCartStoreCoupons, data).then(res => {
      if (res.data.status == 1) {
        if (res.data.result.length > 0) {
          res.data.result.forEach(item => {
            item.use_start_time = utils.timestampToDateFormat(item.use_start_time * 1000);
            item.use_end_time = utils.timestampToDateFormat(item.use_end_time * 1000);
            item.money = item.money.split('.')[0];
            item.condition = item.condition.split('.')[0];
            item.select = false;
          })
        }
        that.setData({
          couponData: res.data.result
        })
      }
    })
  },
  //选择优惠券
  onSelect(e) {
    const that = this;
    let select = e.currentTarget.dataset.select;
    let storeId = e.currentTarget.dataset.store_id;
    let couponIndex = e.currentTarget.dataset.index;
    let couponData = that.data.couponData;
    couponData.forEach((res, index) => {
      if (couponIndex != index) {
        res.select = false
      }
    })
    couponData[couponIndex].select = !select;
    let cart_form_data = {
      "coupon_id": {},
      "user_note": that.data.user_note,
    }
    cart_form_data.coupon_id[storeId] = couponData[couponIndex].select ? couponData[couponIndex].id : ''
    that.setData({
      cart_form_data,
      couponData,
      couponHint: couponData[couponIndex].select ? `满${couponData[couponIndex].money}减${couponData[couponIndex].condition}` : ''
    })

    that.getCart3Data()
  },
  //备注
  getNote(e) {
    const that = this;
    let storeId = e.currentTarget.dataset.store_id
    let user_note = that.data.user_note;
    user_note[storeId] = e.detail.value;
    that.setData({
      user_note,
    })
  },
  getCart2Data() {
    const that = this;
    let data = {
      goods_id: that.data.action == "buy_now" ? that.data.goodsId : "",
      goods_num: that.data.action == "buy_now" ? that.data.goodsNum : "",
      select_store_id: that.data.storeId,
      action: that.data.action,
      address_id: that.data.address_id,
    }
    wx.showLoading({
      title: '加载中...',
    })
    myRequest.EasyHttp.post(api.reqUrls.cart2, data).then(res => {
      wx.hideLoading();
      if (res.data.status == 1) {
        let couponNum = res.data.result.couponNum;
        if (Object.keys(couponNum).length) {
          that.getCoupon()
          res.data.result.storeShippingCartList.forEach(item => {
            if (couponNum[item.store_id]) {
              item.couponNum = couponNum[item.store_id]
            } else {
              item.couponNum = 0
            }
          })
        }
        that.setData({
          cart2Data: res.data.result.storeShippingCartList,
          address: res.data.result.addressList,
          address_id: res.data.result.addressList.address_id,
        })
        that.getCart3Data()

      }
    })
  },
  getCart3Data() {
    const that = this;
    let data = {
      cart_form_data: JSON.stringify(that.data.cart_form_data),
      goods_id: that.data.action == "buy_now" ? that.data.goodsId : "",
      goods_num: that.data.action == "buy_now" ? that.data.goodsNum : "",
      select_store_id: that.data.storeId,
      action: that.data.action,
      address_id: that.data.address_id,
      sm: that.data.sm,
      type: "miniapp",
      act: ""

    }
    wx.showLoading({
      title: '加载中...',
    })
    myRequest.EasyHttp.post(api.reqUrls.cart3, data).then(res => {
      wx.hideLoading();
      if (res.data.status == 1) {
        that.setData({
          cart3Data: res.data.result,
        })

      }
    })
  },
  //添加收货地址
  addSite(e) {
    const that = this;
    let where = e.currentTarget.dataset.where || 0;
    wx.navigateTo({
      url: `/goods/pages/addressList/addressList?where=${where}`,
    })
    // wx.chooseAddress({
    //   success: (res) => {
    //     console.log(res, 99999)
    //     if (res.errMsg = 'chooseAddress:ok') {
    //       that.setData({
    //         address: res
    //       })
    //     }
    //   },
    //   fail: function (err) {
    //     console.log(err)
    //   }
    // })
  },
  debounces: utils.throttle(function (e) {
    this.setData({
      showModal: false
    });
    this.onConfirm()
  }, 5000),
  onConfirm() {
    const that = this;
    let data = {
      goods_id: that.data.action == "buy_now" ? that.data.goodsId : "",
      goods_num: that.data.action == "buy_now" ? that.data.goodsNum : "",
      cart_form_data: JSON.stringify(that.data.cart_form_data),
      select_store_id: that.data.storeId,
      address_id: that.data.address_id,
      action: that.data.action,
      sm: that.data.sm,
      type: "miniapp",
      act: "submit_order",
      wxaddress: JSON.stringify(that.data.address)
    }
    wx.showLoading({
      title: '加载中...',
    })
    myRequest.EasyHttp.post(api.reqUrls.cart3, data).then(res => {

      if (res.data.status == 1) {
        that.setData({
          master_order_sn: res.data.result,
        })
        let amountData = {
          trade_type: "JSAPI",
          master_order_sn: res.data.result,
          account: that.data.cart3Data.order_amount
        }

        // curIndex==0 是微信支付，curIndex==1是会员卡支付
        let curIndex = that.data.curIndex
        if (curIndex == 0) {

          myRequest.EasyHttp.post(api.reqUrls.doPay, amountData).then(prop => {

            if (prop.data.status == 1) {
              if (prop.data.result.banping == 1) {
                let preOrderId = prop.data.result.wx.pre_order
                let merchantId = prop.data.result.wx.merchant_id
                let opAppId = 'wx38a3350891b22014'
                wx.openEmbeddedMiniProgram({
                  appId: opAppId, // 你要打开的小程序appid
                  extraData: { //给B小程序传的参数
                    autoPay: 1,
                  },
                  path: `pages/plugin/pay?preOrderId=${preOrderId}&merchantId=${merchantId}`, // 打开的页面路径，如果为空则打开首页
                  envVersion: 'release', // 要打开的小程序版本 develop 开发版 trial 体验版 release 正式版
                  success(resData) {
                    console.log(resData, 11111)
                    // 打开成功

                    var listener = (props) => {
                      console.log(props, 111)
                      console.log(props.referrerInfo, 222)
                      console.log(props.referrerInfo.extraData, 333)
                      if (!props.referrerInfo.hasOwnProperty('extraData')) {
                        console.log('错误')
                        wx.showModal({
                          content: '付款失败',
                          showCancel: false,
                          confirmText: '我知道了',
                          confirmColor: '#ff5151',
                          success(e) {
                            if (e.confirm) {
                              wx.redirectTo({
                                url: `/goods/pages/order/order`
                              })
                            }
                          }
                        })
                        if (listener) {
                          wx.offAppShow(listener)
                        }
                      }
                      if (props.referrerInfo.extraData.payStatus === '0') {
                        console.log('支付失败')
                        //支付失败
                        //.....
                        wx.showModal({
                          content: '付款失败',
                          showCancel: false,
                          confirmText: '我知道了',
                          confirmColor: '#ff5151',
                          success(e) {
                            if (e.confirm) {
                              wx.redirectTo({
                                url: `/goods/pages/order/order`
                              })
                            }
                          }
                        })
                      }
                      if (props.referrerInfo.extraData.payStatus === '1') {
                        console.log('支付成功')
                        //支付成功
                        //.....

                        setTimeout(() => {
                          wx.redirectTo({
                            url: `/goods/pages/submitOrderSuccess/submitOrderSuccess?orderSn=${that.data.master_order_sn}&type=1`
                          })
                        }, 500)
                      }
                      if (props.referrerInfo.extraData.payStatus === '3') {
                        console.log('用户取消支付')
                        //用户取消支付(订单状态流转为已关闭)
                        //......
                        wx.showModal({
                          content: '付款失败',
                          showCancel: false,
                          confirmText: '我知道了',
                          confirmColor: '#ff5151',
                          success(e) {
                            wx.redirectTo({
                              url: `/goods/pages/order/order`
                            })
                          }
                        })
                      }
                      if (listener) {
                        wx.offAppShow(listener)
                      }
                    };
                    wx.onAppShow(listener)
                  },
                  fail(e) {
                    console.log(e, 999999)
                    // 打开失败
                  },
                })
              } else {
                wx.requestPayment({ // 调取支付
                  timeStamp: prop.data.result.wx.timeStamp,
                  nonceStr: prop.data.result.wx.nonceStr,
                  package: prop.data.result.wx.package,
                  signType: prop.data.result.wx.signType,
                  paySign: prop.data.result.wx.paySign,
                  success(res) {
                    wx.hideLoading();
                    if (res.errMsg == "requestPayment:ok") {
                      wx.redirectTo({
                        url: `/goods/pages/submitOrderSuccess/submitOrderSuccess?orderSn=${that.data.master_order_sn}&type=1`
                      })
                    } else {
                      wx.showModal({
                        content: '付款失败',
                        showCancel: false,
                        confirmText: '我知道了',
                        confirmColor: '#ff5151',
                        success(e) {
                          if (e.confirm) {
                            wx.redirectTo({
                              url: `/goods/pages/order/order`
                            })
                          }
                        }
                      })
                    }
                  },
                  fail(res) {
                    wx.hideLoading();
                    wx.showModal({
                      content: '付款失败',
                      showCancel: false,
                      confirmText: '我知道了',
                      confirmColor: '#ff5151',
                      success(e) {
                        if (e.confirm) {
                          wx.redirectTo({
                            url: `/goods/pages/order/order`
                          })
                        }
                      }
                    })
                  }
                })
              }

            } else {
              wx.hideLoading();
              wx.showModal({
                content: prop.data.msg,
                showCancel: false,
                confirmText: '我知道了',
                confirmColor: '#ff5151',
                success(e) {
                  if (e.confirm) {
                    wx.redirectTo({
                      url: `/goods/pages/order/order`
                    })
                  }
                }
              })
            }
          })
        } else {
          myRequest.EasyHttp.post(api.reqUrls.membercardDopay, amountData).then(prop => {
            wx.hideLoading();
            if (prop.data.status == 1) {
              wx.redirectTo({
                url: `/goods/pages/submitOrderSuccess/submitOrderSuccess?orderSn=${that.data.master_order_sn}&type=1`
              })
            } else if (prop.data.status == -1002) {
              // wx.showModal({
              //   content: '会员卡余额不足，是否去充值？',
              //   confirmText: '去充值',
              //   success(e) {
              //     if (e.confirm) {
              //       wx.redirectTo({
              //         url: `/package/pages/recharge/recharge`,
              //       })
              //     } else if (e.cancel) {
              //       wx.redirectTo({
              //         url: `/goods/pages/order/order`
              //       })
              //     }
              //   }
              // })
              wx.showModal({
                content: prop.data.msg,
                showCancel: false,
                confirmText: '我知道了',
                confirmColor: '#ff5151',
                success(e) {
                  if (e.confirm) {
                    wx.redirectTo({
                      url: `/goods/pages/order/order`
                    })
                  }
                }
              })
            } else {
              wx.showModal({
                content: prop.data.msg,
                showCancel: false,
                confirmText: '我知道了',
                confirmColor: '#ff5151',
                success(e) {
                  if (e.confirm) {
                    wx.redirectTo({
                      url: `/goods/pages/order/order`
                    })
                  }
                }
              })
            }
          })
        }
      } else {
        wx.hideLoading();
        wx.showModal({
          content: res.data.msg,
          showCancel: false,
          confirmText: '我知道了',
          confirmColor: '#ff5151',
          success(e) {
            if (e.confirm) {

            }
          }
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const that = this;
    console.log(options, 77777)
    that.setData({
      goodsId: options.goodsId,
      goodsNum: options.goodsNum,
      storeId: wx.getStorageSync('select_store_id')
    })
    if (options.account) {
      that.setData({
        action: options.account,
      })
    } else {
      that.setData({
        action: '',
      })
    }
    that.getCart2Data()

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage() {

  // }
})